/**
 * Copyright (C) 2010, 2011 Neofonie GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package eu.dicodeproject.analysis.generic;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer.Context;

/**
 * Simple word count mapper
 * Either emits complete content of a column or parts of it using a configured separator  
 */
public class GenericMapper extends TableMapper<Text, IntWritable> {

  private Text content = new Text();
  private final static IntWritable ONE = new IntWritable(1);
  private String separator = null;

  /**
   * Creates the Row Key from current date and query/topic
   */
  protected void setup(Context context) throws IOException, InterruptedException {
    if (context.getConfiguration().get("separator") != null) {
      separator = context.getConfiguration().get("separator");
    }

  }

  @Override
  protected void map(ImmutableBytesWritable row, Result values, Mapper.Context context) throws IOException,
      InterruptedException {

    for (KeyValue keyValue : values.list()) {

      if (separator != null) {

        String field = new String(keyValue.getValue());
        String[] items = field.split(separator);        
        
        for (String item : items) {
          if (!item.equals("")){
          content.set(item);          
          context.write(content, ONE);
          }
        }
      } 
      else {
        content.set(keyValue.getValue());
        context.write(content, ONE);
      }
    }
  }
}
